import {
  getNoticeList,
  getNoticeType,
  getNoticeDetail,
  updateReadStatus,
} from "../services/noticeApi";

const initData = {
  noticeData: {}, // 消息列表
  noticeDetail: {},
  noticePageData: {}, // 我的消息页面专用
  noticeTypes: [],
};

export default {
  namespace: "PageNotice",
  state: {
    ...initData,
  },
  effects: {
    *getNoticeList({ payload }, { call, put }) {
      const { datas, errCode, errMsg, totalCount } = yield call(
        getNoticeList,
        payload,
      );
      yield put({
        type: "get/getNoticeList",
        payload: { noticeList: datas || [], totalCount },
      });
      return { errCode, errMsg, datas };
    },
    *getNoticeType(action, { call, put, select }) {
      const { noticeTypes } = yield select(({ PageNotice: m })=> m);
      if (!noticeTypes || (noticeTypes.length === 0)) {
        const { errCode, datas } = yield call(getNoticeType);
        yield put({
          type: "set/noticeTypes",
          payload: errCode === 0 ? datas : [],
        });
      }
    },
    *getNoticeListPage({ payload }, { call, put }) {
      const { datas, errCode, errMsg, errortext, totalCount } = yield call(
        getNoticeList,
        payload,
      );
      yield put({
        type: "get/getNoticeListPage",
        payload: { noticeList: datas || [], totalCount },
      });
      return { errCode, errMsg: errMsg || errortext, datas, totalCount };
    },
    *getNoticeDetail({ payload }, { call, put }) {
      const { datas, errCode, errortext, errMsg } = yield call(
        getNoticeDetail,
        payload,
      );
      yield put({ type: "get/getNoticeDetail", payload: datas || {} });
      return { errCode, errMsg: errMsg || errortext, datas };
    },
    *updateReadStatus({ payload }, { call }) {
      const { errCode, errMsg } = yield call(updateReadStatus, payload);
      return { errCode, errMsg };
    },
  },
  reducers: {
    "get/getNoticeList": (state, { payload }) => ({
      ...state,
      noticeData: payload,
    }),
    "set/noticeTypes": (state, { payload }) => ({
      ...state,
      noticeTypes: payload,
    }),
    "get/getNoticeListPage": (state, { payload }) => ({
      ...state,
      noticePageData: payload,
    }),
    "get/getNoticeDetail": (state, { payload }) => ({
      ...state,
      noticeDetail: payload,
    }),
    clearData: () => ({ ...initData }),
  },
};
